import * as echarts from 'echarts'
export class MyChart {
    constructor(container) {
        this.container = container
        this.chart = null
        this.resizeObserver = null
        this.initChart()
    }

    initChart() {
        if (this.chart) {
            this.chart.dispose()
        }
        this.chart = echarts.init(this.container)
        this.onResize()
    }

    drawChart(source, cb, baseOption = {}) {
        cb?.(source, baseOption)
        this.chart.setOption({
            ...baseOption,
            dataset: {
                source,
            },
        })
    }

    setOption(option) {
        if (this.chart) {
            this.chart.setOption(option)
        }
    }

    resize() {
        if (this.chart) {
            this.chart.resize()
        }
    }

    dispose() {
        if (this.chart) {
            this.chart.dispose()
            this.chart = null
            this.offResize()
        }
    }

    onResize() {
        this.resizeObserver = new ResizeObserver(() => this.resize())
        this.resizeObserver.observe(this.container)
    }

    offResize() {
        if (this.resizeObserver) {
            this.resizeObserver.unobserve(this.container)
            this.resizeObserver = null
        }
    }
}
